<template>
  <div>
    <!-- 微博登录的对话框 -->
    <el-dialog
      class="dialog-wrap"
      title="分享文章"
      :visible.sync="articleDialogFormVisible"
      @close="articleDialogClosed"
    >
      <el-form
        :model="articleForm"
        :rules="articleFormRules"
        ref="articleFormRef"
        label-width="100px"
      >
        <el-form-item
          label="文章分类"
          :label-width="formLabelWidth"
          prop="labelId"
        >
          <div class="article-cat-wrap">
            <el-select
              v-model="articleForm.labelId"
              placeholder="请选择文章的分类"
              @change="selectArticleCatChange"
            >
              <el-option
                v-for="item in articleCateList"
                :key="item.value"
                :label="item.label"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item
          label="话题分类"
          :label-width="formLabelWidth"
          prop="topicCat"
        >
          <div class="topic-cat-wrap">
            <!-- 选择热门话题分类 -->
            <el-autocomplete
              class="inline-input"
              v-model="selectedTopicHotRank"
              :fetch-suggestions="getTopicHotRank"
              placeholder="请输入(选择)话题分类(可选)"
              @select="selectTopicHotRank"
              @change="inputTopicChange"
              type="textarea"
            ></el-autocomplete>
          </div>
        </el-form-item>
        <el-form-item
          label="正文"
          :label-width="formLabelWidth"
          prop="content"
          class="article-content"
        >
          <el-input
            @input="inputContent"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 10 }"
            placeholder="有什么新鲜事分享给大家？"
            v-model="articleForm.content"
          >
          </el-input>
          <i
            :class="[
              'iconfont',
              'icon',
              'icon-xiaolian',
              showEmojiPicker ? 'active' : '',
            ]"
            @click="showEmojiPicker = !showEmojiPicker"
          ></i>
          <div class="emoji-picker-wrap">
            <VEmojiPicker
              class="emoji-picker"
              @select="selectEmoji"
              v-show="showEmojiPicker"
            />
          </div>
        </el-form-item>
      </el-form>
      <div class="pic-video-wrap">
        <!-- 上传图片 -->
        <template v-if="fileCat === 1">
          <div class="pic-video-title">
            <span>上传图片</span>
          </div>
          <el-upload
            :action="defalutUploadUrl"
            list-type="picture-card"
            :headers="headerObj"
            :on-preview="handlePicCardPreview"
            :on-remove="handlePicRemove"
            :file-list="fileList"
            multiple
            name="files"
            :on-success="fileUploadSuccess"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </template>
        <!-- 上传视频 -->
        <template v-else-if="fileCat === 2">
          <div class="pic-video-title">
            <span>上传视频</span>
          </div>
          <el-upload
            v-if="!articleForm.images[0]"
            :action="defalutUploadUrl"
            :headers="headerObj"
            :show-file-list="false"
            list-type="picture-card"
            :before-upload="beforeUploadVideo"
            name="files"
            :on-success="handleVideoSuccess"
          >
            <i class="el-icon-plus"></i>
          </el-upload>

          <div class="video-wrap" v-if="articleForm.images[0]">
            <video
              :src="userUrl(articleForm.images[0])"
              class="video"
              controls="controls"
            >
              您的浏览器不支持视频播放
            </video>
            <i class="el-icon-circle-close delete" @click="deleteVideo"></i>
          </div>
        </template>
      </div>
      <div class="bottom-wrap">
        <el-row
          ><el-col :span="12">
            <div class="icon-wrap">
              <i
                :class="[
                  'el-icon-picture-outline',
                  'icon',
                  fileCat === 1 ? 'fileActive' : '',
                ]"
                @click="fileCat = fileCat === 1 ? 0 : 1"
              ></i>
              <i
                :class="[
                  'el-icon-video-camera-solid',
                  'icon',
                  fileCat === 2 ? 'fileActive' : '',
                ]"
                @click="fileCat = fileCat === 2 ? 0 : 2"
              ></i>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="article-give-status-wrap">
              <div class="article-status-wrap">
                <div class="article-status-more">
                  <el-popover
                    placement="bottom"
                    title="文章状态管理"
                    trigger="hover"
                  >
                    <div class="article-status-item-wrap">
                      <span class="article-status-text">能否点赞</span
                      ><el-switch
                        v-model="articleMoreStatus.isLike"
                        active-color="#ff8200"
                        inactive-color="#939393"
                      >
                      </el-switch>
                    </div>
                    <div class="article-status-item-wrap">
                      <span>能否分享</span
                      ><el-switch
                        v-model="articleMoreStatus.isForward"
                        active-color="#ff8200"
                        inactive-color="#939393"
                      >
                      </el-switch>
                    </div>
                    <div class="article-status-item-wrap">
                      <span>能否收藏</span
                      ><el-switch
                        v-model="articleMoreStatus.isCollection"
                        active-color="#ff8200"
                        inactive-color="#939393"
                      >
                      </el-switch>
                    </div>
                    <div class="article-status-item-wrap">
                      <span>能否评论</span
                      ><el-switch
                        v-model="articleMoreStatus.isComment"
                        active-color="#ff8200"
                        inactive-color="#939393"
                      >
                      </el-switch>
                    </div>

                    <i class="el-icon-more" slot="reference"></i>
                  </el-popover>
                </div>
                <div class="article-status-all">
                  <el-dropdown @command="handleArticleStatus">
                    <span class="el-dropdown-link">
                      {{ articleStatus
                      }}<i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item :command="1">公开</el-dropdown-item>
                      <el-dropdown-item :command="0"
                        >仅自己可见</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              </div>

              <div class="article-wrap" @click="publishArticle">
                <div class="article">发送</div>
              </div>
            </div>
          </el-col></el-row
        >
      </div>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog :visible.sync="picPreviewDialogVisible">
      <img width="100%" :src="picPreviewUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import config from "@/config/index.js";
import { mapState, mapMutations, mapActions } from "vuex";
import { VEmojiPicker } from "v-emoji-picker";
export default {
  components: { VEmojiPicker },
  // 控制发布文章对话框的显示与否
  props: ["showArticleDialog"],
  computed: {
    ...mapState("m_system", ["articleCateList"]),
    articleDialogFormVisible: {
      get() {
        return this.showArticleDialog;
      },
      set(value) {
        this.$emit("articleDialogClosed");
      },
    },
    // 文章的状态
    articleStatus() {
      if (this.articleForm.isPublish == 1) {
        return "公开";
      } else if (this.articleForm.isPublish == 0) {
        return "私密";
      }
    },
  },
  created() {
    // 获取文章分类列表
    if (this.articleCateList.length <= 0) this.getArticleCatList();
  },
  data() {
    return {
      // 默认文件上传地址
      defalutUploadUrl: config.defalutUploadUrl,
      //   图片上传组件headers请求头对象
      headerObj: {
        Authorization:
          localStorage.token_type + " " + localStorage.access_token,
      },
      // 左侧文本的宽度
      formLabelWidth: "100px",
      // 控制发布文章的显示与否
      //   registerDialogFormVisible: true,
      // 表情包的显示与否
      showEmojiPicker: false,
      // 文章的表单数据
      articleForm: {
        labelId: "",
        topicId: "",
        content: "",
        images: [],
        type: "0",
        // 经纬度
        longitude: 0,
        dimension: 0,
        // 是否公开
        isPublish: 1,
        // 能否点赞
        isLike: 1,
        // 能否分享
        isForward: 1,
        // 能否收藏
        isCollection: 1,
        // 能否评论
        isComment: 1,
        // 父文章
        pid: 0,
      },
      articleMoreStatus: {
        // 能否点赞
        isLike: true,
        // 能否分享
        isForward: true,
        // 能否收藏
        isCollection: true,
        // 能否评论
        isComment: true,
      },
      // 登录表单的验证规则
      articleFormRules: {
        articleCat: [
          { required: true, message: "请选择文章分类", trigger: "blur" },
        ],
        content: [{ required: true, message: "请输入正文", trigger: "blur" }],
      },
      // 文章的分类
      articleCat: [],
      // 默认文章分类的选择值
      selectedArticleCatValue: "",
      // 默认文章热门话题分类的选择值
      selectedTopicHotRank: "",
      // 上传图片或视频 0-没选 1-图片 2-视频
      fileCat: 0,
      // 上传的文件列表
      // fileList: [],
      fileList: [],
      // 控制图片预览对话框的显示与否
      picPreviewDialogVisible: false,
      // 当前预览的图片地址
      picPreviewUrl: "",
    };
  },
  methods: {
    ...mapActions("m_system", ["getArticleCatList"]),
    // 用户的头像(单张图片)
    userUrl(userUrl) {
      if (!userUrl) return null;
      // 用户的头像加地址前缀
      return config.defalutBaseURLPic + userUrl;
    },
    //   发布文章
    publishArticle() {
      console.log(this.articleForm.content);
      this.$refs.articleFormRef.validate(async (valid) => {
        if (!valid) return;
        // 发布文章
        for (let item in this.articleMoreStatus) {
          this.articleForm[item] = this.articleMoreStatus[item] ? 1 : 0;
        }
        console.log(this.articleForm);
        const { msg, code } = await this.$http.post(
          "/api/tweet/add",
          this.articleForm
        );
        console.log(msg);
        if (code !== 200) {
          // 隐藏发布文章的对话框
          this.$emit("articleDialogClosed");
          return this.$message.error("发布文章失败！");
        }
        this.$message.success("发布文章成功！");
        // 隐藏发布文章的对话框
        this.$emit("articleDialogClosed");
      });
    },
    // 重置表单
    resetArticleForm() {
      this.$refs.articleFormRef.resetFields();
    },
    // 发布文章对话框关闭事件
    articleDialogClosed() {
      this.$refs.articleFormRef.resetFields();
      this.selectedTopicHotRank = "";
      this.articleForm.images = [];
      this.fileList = [];
      this.fileCat = 0;
      for (let item in this.articleMoreStatus) {
        this.articleMoreStatus[item] = true;
      }
    },
    // 选择文章分类事件
    selectArticleCatChange(value) {
      // console.log(this.articleForm.labelId, value);
    },
    // 获取热门话题分类
    getTopicHotRank(inputValue, cb) {
      let data = [
        { value: "你会对18岁的自己说些什么", topicId: 1 },
        { value: "为什么越长大越喜欢怀旧", topicId: 2 },
        { value: "你心中爱的味道是什么", topicId: 3 },
        { value: "多一颗芯对拍照有啥影响", topicId: 4 },
      ];
      cb(data);
    },
    // 选择热门话题分类
    selectTopicHotRank(value) {
      // 赋值topicId
      this.articleForm.topicId = value.topicId;
      // console.log(value);
    },
    // 输入话题分类
    inputTopicChange(value) {
      // 新建话题 请求
      this.articleForm.topicId = 1;
      // console.log(value);
    },
    // 选择文章的分享状态
    handleArticleStatus(value) {
      this.articleForm.isPublish = value;
    },
    // 输入正文内容
    inputContent(value) {
      // console.log(value);
      // console.log(this.articleForm.content);
    },
    // 成功上传文件的回调函数
    fileUploadSuccess(response, file, fileList) {
      // console.log(response);
      if (response.code == 200) {
        this.articleForm.images.push(response.result[0]);
      }
    },
    // 处理文件删除
    handlePicRemove(file, fileList) {
      let images = this.articleForm.images;
      let url = file.response.result[0];
      let index = images.findIndex((v) => v == url);
      this.articleForm.images.splice(index, 1);
    },
    // 处理文件的预览
    handlePicCardPreview(file) {
      this.picPreviewUrl = file.url;
      this.picPreviewDialogVisible = true;
    },
    // 选择表情包
    selectEmoji(emoji) {
      this.articleForm.content = this.articleForm.content + emoji.data;
    },
    // 上传视频前函数
    beforeUploadVideo(file) {
      const videoFile = file.size / 1024 / 1024 < 300;
      if (["video/mp4"].indexOf(file.type) == -1) {
        this.$message.error("请上传MP4的视频格式");
        return false;
      }
    },
    // 获取上传视频的地址
    handleVideoSuccess(res, file) {
      console.log(res, file);
      let { code, result } = res;
      if (code != 200) this.$message.error("视频上传失败，请重新上传！");
      this.articleForm.images.push(result[0]);
    },
    // 删除视频
    deleteVideo() {
      this.articleForm.images.pop();
    },
  },
};
</script>

<style scoped lang="less">
.dialog-wrap {
  // text-align: left;
  /deep/.el-dialog__title {
    width: 120px;
    color: #ffa00a;
    /deep/.inline-input {
      width: 100px;
    }
  }
  .article-cat-wrap {
    text-align: left;
  }
  .topic-cat-wrap {
    text-align: left;
  }
  .article-content {
    text-align: left;
    .icon {
      font-size: 20px;
      cursor: pointer;
    }
    .active {
      color: #ff8200;
    }

    .emoji-picker-wrap {
      position: relative;
      // 正文输入内容
      .emoji-picker {
        position: absolute;
        // margin-top: -10px;
        width: 100%;
        // height: 300px;
        z-index: 2;
        box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
      }
    }
  }

  .pic-video-wrap {
    margin-top: -20px;
    text-align: left;
    margin-bottom: 5px;
    margin-left: 100px;
    .pic-video-title {
      margin-bottom: 5px;
      span {
        color: rgb(177, 177, 177);
      }
    }
    .video-wrap {
      position: relative;
      .video {
        width: 300px;
      }
      .delete {
        cursor: pointer;
        font-size: 30px;
        position: absolute;
        color: #ff8200;
        left: 285px;
        top: -10px;
      }
    }
  }
  .bottom-wrap {
    padding-left: 100px;
    padding-top: 10px;
    text-align: left;
    border-top: rgb(240, 240, 240) 1px solid;
    .icon-wrap {
      width: 20%;
      display: flex;
      justify-content: space-between;
      .icon {
        font-size: 24px;
        cursor: pointer;
      }
      .icon-xiaolian {
        // color: #ff8200;
      }
      .fileActive {
        color: #ff8200;
      }
    }
    .article-give-status-wrap {
      display: flex;
      justify-content: right;
      .article-status-wrap {
        display: flex;
        height: 40px;
        line-height: 40px;
        margin-right: 10px;
        .article-status-more {
          margin-right: 10px;
          line-height: 40px;
          height: 40px;
          .article-status-item-wrap {
            display: flex;
            justify-content: space-around;
            align-items: center;
            margin-bottom: 2px;
            span {
              color: #333;
              padding-right: 10px;
              display: inline-block;
            }
          }
          .el-icon-more {
            font-size: 20px;
            color: #939393;
            cursor: pointer;
          }
        }

        .article-status-all {
          .el-dropdown-link {
            cursor: pointer;
            color: #939393;
            font-size: 12px;
          }
        }
      }
      .article-wrap {
        color: white;
        display: flex;
        justify-content: center;
        font-weight: 540;
        text-align: right;
        .article {
          opacity: 0.6;
          width: 90px;
          background-color: #ff8200;
          text-align: center;
          height: 40px;
          line-height: 40px;
          cursor: pointer;
          font-size: 18px;
          font-weight: 580;
          border-radius: 30px;
        }
      }
    }
  }
}
</style>